<template>
	<page-header title="商品详情" background="#F7F0E6" :needHome="needHome"
		style="position: fixed;width: 100%;top: 0;z-index: 100;"></page-header>
	<view class="page-detail" :style="{paddingTop:`${50+securityHeight*2}rpx`}">
		<!-- 头部 -->
		<!--  -->
		<!-- <view class="det-header" :style="{ opacity: topTabOpacity, zIndex: topTabOpacity > 0.2 ? '1' : '-1' }">
      <view :class="['item', topTabSts === 0 ? 'active' : '']" @tap="hanleTopTabClick(0)">
        商品
      </view>
      <view :class="['item', topTabSts === 2 ? 'active' : '']" @tap="hanleTopTabClick(2)">
        详情
      </view>
    </view> -->

		<!-- 大图 -->
		<swiper class="pic-box" indicator-dots="true" indicator-color="rgba(255,252,255, .3)"
			indicator-active-color="rgba(255,252,255, .6)" autoplay="true" circular="true">
			<swiper-item v-for="(img, imgIdx) in imgList" :key="imgIdx" class="item">
				<image :src="img" mode="aspectFill" />
			</swiper-item>
		</swiper>
		<!-- 倒计时窗口 -->
		<view class="countdown-popup" v-if="timeLeft.total > 0">
			<view>
				倒计时
				<span class='countdownTime'>
					{{ timeLeft.days }}
				</span>
				天
				<span class='countdownTime'>
					{{ timeLeft.hours }}
				</span>时<span class='countdownTime'>{{ timeLeft.minutes }}</span>
				分
				<span class='countdownTime'>
					{{ timeLeft.seconds }}
				</span>
				秒
			</view>
			<view style='margin-top: 15rpx;'>
				开售时间：9月14日 22:00
			</view>
		</view>

		<!-- 名称、价格 -->
		<view class="name-box">
			<view class="price-box">
				<price-point :price="defaultSku.priceFee" :point="defaultSku.pointPrice" :size="52"></price-point>
				<view class="marketPrice">市场价<price-point :price="prodInfo.marketPrice" :size="30"
						color="#999"></price-point>
				</view>
			</view>
			<view class="name">
				<view class="hot">热销</view>
				<text style="color:#000">{{ prodInfo.name }}</text>
			</view>
			<view class="action-box">
				<view>发货地：浙江 台州</view>
				<view class="stock">
					仅剩{{ defaultSku.stock }}件
				</view>
			</view>
		</view>

		<view class="block"></view>

		<!-- sku、配送 -->
		<view class="det-con">
			<view class="item">
				<view class="tit">
					已选
				</view>
				<view class="con sku-con" @tap="isShowSkuPopup = true">
					<view v-if="defaultSku.skuName" class="s-item">
						{{ defaultSku.skuName }} {{ ' ' + prodNumber }} 件
					</view>
				</view>
			</view>
		</view>

		<view class="block"></view>

		<!-- 店铺 -->
		<!-- <view class="shop-box">
      <view class="shop-info">
        <view class="info">
          <view class="img">
            <image :src="shopInfo.shopLogo" />
          </view>
          <view class="text">
            <view class="name">
              {{ shopInfo.shopName }}
            </view>
            <view class="focus-box">
              <view v-if="shopInfo.type === 1" class="self">
                自营
              </view>
            </view>
          </view>
        </view>
        <view class="go-shop" @tap="toShopIndex">
          进店逛逛
        </view>
      </view>
    </view> -->

		<!-- 详情 -->
		<div class="det-det">
			<div class="tit">
				商品详情
			</div>
			<div class="con">
				<rich-text :nodes="prodDetail" />
			</div>
		</div>

		<!-- 底部 -->
		<view class="det-foot">
			<view class="actions">
				<button class="shareButton" open-type="share">
					<view class="img">
						<image src="/static/images/share.png" />
					</view>
					<view class="text">
						分享
					</view>
				</button>
				<view class="item" @tap="toCart">
					<view class="img">
						<image src="/static/images/detail-cart.png" />
						<view v-if="cartCount" class="mark">
							{{ cartCount }}
						</view>
					</view>
					<view class="text">
						购物车
					</view>
				</view>
			</view>
			<view class="btns">
				<view class="btn" @tap="addCart">
					加入购物车
				</view>
				<view class="btn btn-r" @tap="goSubmit">
					立即购买
				</view>
			</view>
		</view>




		<!-- 选择sku弹窗 -->
		<view class="popup" :class="{ show: isShowSkuPopup }">
			<!-- <SkuSelectPopup :prod-info="prodInfo" /> -->
			<view class="popup-mask" @tap="closePopup" />
			<view class="popup-con-bottom check-sku">
				<view class="goods-box">
					<view class="img">
						<image :src="prodInfo.mainImgUrl" mode="aspectFill" />
					</view>
					<view class="info">
						<view class="name">
							{{ prodInfo.name }}
						</view>
						<price-point :price="defaultSku.priceFee" :point="defaultSku.pointPrice"
							:size="45"></price-point>
					</view>
					<view class="close" @tap="closePopup">
						<image src="../../static/images/payment-close.png" />
					</view>
				</view>
				<view class="con-box">
					<view v-if="defaultSku.skuName" class="sku-item">
						<view class="item-tit">
							规格
						</view>
						<view class="item-box">
							<!-- 							<view v-for="(skuItem, index) in Data.skuList" :key="index"
								:class="['item-item', defaultSku.skuName == skuItem.skuName ? 'active' : '']"
								@tap="toChooseItem(skuItem)">
								{{ skuItem.skuName }}
							</view> -->
							<view v-for="(item, index) in skuLevels" :key="index" class="item-box">

								<view v-for="(childItem, childIndex) in item.options" :key="childIndex"
									:class="['item-item', itemEnable(childItem,index)?(selectedSkuNames[index] == childItem ? 'active' : ''):'disable']"
									@tap="toChooseSkuName(childItem, index)">
									{{ childItem }}
								</view>
							</view>
						</view>
					</view>
					<view class="prod-number">
						<view class="item-tit">
							数量
						</view>
						<view class="number-box">
							<view :class="['minus', prodNumber === 1 ? 'limit' : '']" @tap="changeNumber(-1)" />
							<input v-model="prodNumber" type="number" class="number" maxlength="4">
							<view :class="['plus', isMaxProdNumber ? 'limit' : '']" @tap="changeNumber(1)" />
						</view>
					</view>
					<view v-if="defaultSku.needIdCard && Data.skuPopConfirmType == 1">
						<view class="item-tit">
							实名观演人
							<view class="button" @tap="toViewer">添加</view>
						</view>
						<view class="popup-item" v-for="(item, index) in Data.idCardList" :key="index"
							@tap="selectIdCards(item.id)">
							<view>
								<view class="name">{{ item.name }}</view>
								<view class="card">{{queryType(item.queryType)}} {{ handleIdCard(item.idCard) }}</view>
							</view>
							<uni-icons color="#DA9974" type="checkbox" size="20"
								v-if="Data.selectIdCard.includes(item.id)"></uni-icons>
							<uni-icons color="#DA9974" type="circle" size="20" v-else></uni-icons>
						</view>
					</view>
				</view>
				<view class="btn-box">
					<view class="btn" @tap="skuPopupConfirm" v-if="Data.defaultSku.stock > 0 ">
						确定
					</view>
					<view class="btn gray" v-else-if="Data.defaultSku.skuId == 0">
						请选择规格
					</view>
					<view class="btn gray" v-else>
						商品已售罄
					</view>
				</view>
			</view>
		</view>
	</view>
	<uni-popup ref="popup" type="center" borderRadius="10px" :mask-click="false">
		<view class="popupBox">
			<image :src="addDomain('/static/viwerPopup.png')"></image>
			<view class="button" @tap="toViewer">预填实名观演人</view>
			<view class="ready" @tap="popupClose">
				确认并知悉
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
	import {
		onShareTimeline,
		onShareAppMessage
	} from '@dcloudio/uni-app';
	import {
		onMounted,
		reactive,
		ref,
		watch
	} from 'vue'

	const popup = ref(null)

	const Data = reactive({
		isShowSkuPopup: false, // 显示sku弹窗
		cloudShopHaveView: [], // 商品流量记录
		spuId: 0, // 商品id
		shopId: 0,
		prodInfo: {}, // 商品详情
		shopInfo: {}, // 店铺详情
		deliveryModeVO: {}, // 商品配送方式
		imgList: [], // 商品轮播图
		prodDetail: '', // 商品详情富文本
		selectIdCard: [], //已选择身份证信息
		selectIdCount: 0,
		idCardList: [], //身份证信息列表
		// pageScorllTop: 0, // 页面滚动的高度
		topTabSts: 0, // 顶部 topTab 选中的项目
		topTabOpacity: 0, // 顶部 topTab 的透明度
		// sku 商品规格
		needIdCard: false, // 是否强实名
		defaultSku: {},
		skuList: [],
		skuPopConfirmType: 0, // 规格弹窗类型: 0普通sku切换; 1加入购物车; 2立即购买
		prodNumber: 1, // 商品数量
		hasMaxNumber: 0, // 是否限购
		maxNum: 10, // 限购数量(仅团购商品) TODO:假的,以后要删的~()
		isMaxProdNumber: false, // 是否达到限购或达到最大库存
		cartCount: 0,
		needHome: false, // 返回按键是否跳转首页，如果页面来自分享，返回按键跳转首页
		skuTree: [],
		selectedSkuNames: [],
		skuLevels: []
	})
	const {
		isShowSkuPopup,
		cloudShopHaveView,
		prodInfo,
		shopInfo,
		imgList,
		prodDetail,
		selectIdCard,
		selectIdCount,
		idCardList,
		topTabSts,
		topTabOpacity,
		needIdCard,
		defaultSku,
		skuList,
		prodNumber,
		isMaxProdNumber,
		cartCount,
		needHome,
		skuTree,
		selectedSkuNames,
		skuLevels
	} = toRefs(Data)

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad((options) => {
		if (options.spuId) {
			Data.spuId = options.spuId
		}
	})

	onShow(() => {
		let pages = getCurrentPages()
		if (pages.length === 1) {
			Data.needHome = true
		}
		// 获取商品详情
		getProdInfo()
		// 获取购物车数字
		getCartCount()
		// 获取观演人数据
		getIdCardList()
	})

	onPageScroll((e) => {
		Data.topTabOpacity = e.scrollTop / 46
	})

	watch(() => Data.prodNumber, (nv) => {
		if (nv >= Data.defaultSku.stock) {
			Data.isMaxProdNumber = true
		} else {
			Data.isMaxProdNumber = false
		}
	})

	watch(() => Data.defaultSku, () => {
		Data.prodNumber = 1
		if (Data.prodNumber >= Data.defaultSku.stock) {
			Data.isMaxProdNumber = true
			Data.prodNumber = Data.defaultSku.stock
		} else {
			Data.isMaxProdNumber = false
		}
	})

	/**
	 * 获取商品详情
	 */
	const getProdInfo = () => {
		uni.showLoading()
		const params = {
			url: '/mall4cloud_product/ua/spu/prod_info',
			method: 'GET',
			data: {
				spuId: Data.spuId
			}
		}
		http.request(params).then((res) => {
			Data.shopId = res.shopId
			getShopInfo()
			uni.hideLoading()
			let imgList = []
			if (res.imgUrls) {
				imgList = res.imgUrls.split(',')
			}
			Data.prodInfo = res
			Data.deliveryModeVO = res.deliveryModeVO
			Data.prodDetail = util.formatHtml(res.detail)
			Data.imgList = imgList
			Data.skuList = res.skus

			// 组装sku
			Data.skuTree = splitSkuTree(Data.skuList)
			initializeSkuLevels();
			groupSkuProp(res.skus, res.priceFee, res.pointPrice)
			// 判断是否需要强实名
			if (Data.defaultSku.needIdCard == 1) {
				Data.needIdCard = true
				uni.getStorage({
					key: 'cloudShopHaveView',
					success(res) {
						if (Array.isArray(res.data)) {
							Data.cloudShopHaveView = res.data
						} else {
							Data.cloudShopHaveView = []
						}
						if (!Data.cloudShopHaveView.includes(Number(Data.spuId))) {
							popupOpen()
						}
					},
					fail(res) {
						uni.setStorageSync('cloudShopHaveView', Data.cloudShopHaveView)
						popupOpen()
					}
				})
			}
		})
	}

	const groupSkuProp = (skuList, defaultPrice, defaultPoint) => {
		// if (skuList.length == 1) {
		// 	Data.defaultSku = skuList[0] || {}
		// 	Data.selectedSkuNames = Data.defaultSku.skuName.split('_')
		// 	return
		// }
		// for (let i = 0; i < skuList.length; i++) {
		// 	if (skuList[i].priceFee == defaultPrice && skuList[i].pointPrice == defaultPoint) {
		// 		Data.defaultSku = skuList[i]
		// 		Data.selectedSkuNames = Data.defaultSku.skuName.split('_')
		// 		return
		// 	}
		// }
		// Data.defaultSku = skuList[0]
		// Data.selectedSkuNames = Data.defaultSku.skuName.split('_')
	}

	const toChooseItem = (skuItem) => {
		Data.defaultSku = skuItem
	}

	const toChooseSkuName = (childItem, index) => { // 更新用户选择的规格
		Data.selectedSkuNames[index] = childItem;
		// 清除之后的选择
		Data.selectedSkuNames.splice(index + 1);
		Data.skuLevels.splice(index + 1);

		// 获取当前选择项对应的下一级
		let nextLevel = Data.skuLevels[index].nextLevel[childItem];

		if (nextLevel && typeof nextLevel === 'object' && !nextLevel.skuId) {
			const options = Object.keys(nextLevel);
			Data.skuLevels.push({
				options,
				nextLevel
			});
		}
		if (nextLevel.skuId) {
			setDefaultSkuById(nextLevel.skuId)
		} else {
			setDefaultSkuById(null)
		}
	}

	const splitSkuTree = (skuList) => {
		let skuTree = {};
		skuList.forEach(({
			skuId,
			skuName
		}) => {
			// 按照 '_' 分割skuName，获取规格属性数组
			let attrs = skuName.split('_');

			// 从根节点开始
			let currentLevel = skuTree;

			// 遍历规格属性
			attrs.forEach((attr, index) => {
				// 如果当前属性不存在于当前级别中，则创建它
				if (!currentLevel[attr]) {
					currentLevel[attr] = {};
				}

				// 如果是最后一个属性，存储skuId
				if (index === attrs.length - 1) {
					currentLevel[attr].skuId = skuId;
				} else {
					// 否则继续深入到下一级别
					currentLevel = currentLevel[attr];
				}
			});
		});
		return skuTree;
	}
	const initializeSkuLevels = () => {
		console.log(Data.skuTree)
		let currentLevel = Data.skuTree;
		Data.skuLevels = [];

		let level = 0
		while (currentLevel && typeof currentLevel === 'object' && !currentLevel.skuId) {
			const options = Object.keys(currentLevel);
			Data.skuLevels.push({
				options,
				nextLevel: currentLevel
			});
			currentLevel = currentLevel[options[0]]; // 初始化时选取第一个选项进行深入
			Data.selectedSkuNames[level] = options[0]
			if (currentLevel.skuId) {
				setDefaultSkuById(currentLevel.skuId)
			}
			level = level + 1
		}
		console.log(Data.skuLevels)
	}
	const setDefaultSkuById = (skuId) => {
		if (skuId) {
			Data.skuList.forEach((item) => {
				if (item.skuId == skuId) {
					console.log(item)
					Data.defaultSku = item
				}
			})
		} else {
			Data.defaultSku = {
				freeShip: 0,
				imgUrl: "",
				marketPriceFee: 0,
				needIdCard: 0,
				pointPrice: 0,
				priceFee: '请选择规格',
				properties: "",
				skuId: 0,
				skuName: "请选择规格",
				stock: 0
			}
		}
	}
	/**
	 * 规格弹窗底部确定按钮
	 */
	const skuPopupConfirm = () => {
		if (!uni.getStorageSync('cloudToken')) {
			uni.showModal({
				title: '提示',
				content: '该功能登录后开放哦',
				confirmText: '去登录',
				success: modalRes => {
					if (modalRes.confirm) {
						// 跳转登录页面
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}
				}
			})
			return
		}
		if (!Data.defaultSku.stock) {
			uni.showToast({
				title: '所选规格无货',
				duration: 2000,
				icon: 'none'
			})
			return
		}
		if (Data.skuPopConfirmType === 1) {
			let prodNumber = parseInt(Data.prodNumber)
			if (Data.defaultSku.needIdCard && Data.selectIdCount != prodNumber) {
				uni.showToast({
					title: `请选择${Data.prodNumber}位观演人`,
					duration: 2000,
					icon: 'none'
				})
				return
			}
			const params = {
				url: '/mall4cloud_product/a/shop_cart/change_item',
				method: 'POST',
				data: {
					skuId: Data.defaultSku.skuId,
					spuId: Data.defaultSku.spuId,
					count: Data.prodNumber,
					idCards: Data.defaultSku.needIdCard ? handleSelectIdCard() : ''
				}
			}
			http.request(params).then(() => {
				uni.showToast({
					title: '加入购物车成功~',
					duration: 2000,
					icon: 'none'
				})
				getCartCount()
			})
		}
		if (Data.skuPopConfirmType === 2) {
			uni.setStorageSync('cloudShopCartItem', JSON.stringify({
				count: Data.prodNumber,
				shopId: Data.prodInfo.shopId,
				skuId: Data.defaultSku.skuId,
				spuId: Data.spuId
			}))
			uni.navigateTo({
				url: '/pages/submit-order/submit-order?orderEntry=1'
			})
		}
		Data.skuPopConfirmType = 0
		closePopup()
	}

	const handleSelectIdCard = () => {
		let arr = []
		Data.idCardList.forEach(item => {
			if (Data.selectIdCard.includes(item.id)) {
				arr.push(`${item.idCard}:${item.name}:${item.type}`)
			}
		})
		return arr.join(",")
	}

	/**
	 * 加入购物车按钮
	 */
	const addCart = () => {
		Data.skuPopConfirmType = 1
		Data.isShowSkuPopup = true
	}

	/**
	 * 修改商品数量
	 */
	const changeNumber = (num) => {
		let prodNumber = parseInt(Data.prodNumber)

		if (num < 0) { // 点击数量-
			if (prodNumber === 1) {
				return
			} else {
				prodNumber += num
			}
		} else { // 点击数量+
			// 限购判断
			if (Data.hasMaxNumber) {
				if (prodNumber >= Data.maxNum) {
					uni.showToast({
						title: `限购 ${Data.maxNum} 件`,
						duration: 2000,
						icon: 'none'
					})
				}
				if (Data.defaultSku.stock < prodNumber) {
					uni.showToast({
						title: '库存不足',
						duration: 2000,
						icon: 'none'
					})
				}
				if (prodNumber < Data.maxNum) {
					prodNumber += num
				}
			} else { // 不限购
				if (prodNumber < Data.defaultSku.stock) {
					prodNumber += num
				} else {
					uni.showToast({
						title: '库存不足',
						duration: 2000,
						icon: 'none'
					})
				}
			}
		}
		Data.prodNumber = prodNumber
	}

	/**
	 * 获取店铺信息
	 */
	const getShopInfo = () => {
		const params = {
			url: '/mall4cloud_multishop/ua/shop_detail/head_info',
			method: 'GET',
			data: {
				shopId: Data.shopId
			}
		}
		http.request(params).then((res) => {
			Data.shopInfo = res
		})
	}
	/**
	 * 判断商品规格是否可用
	 */
	const itemEnable = (childItem, index) => {
		let childSkuName = Data.selectedSkuNames.slice(0, index).join("_") + '_' + childItem;
		let result = true
		Data.skuList.forEach((item) => {
			if (item.skuName == childSkuName) {
				result = item.stock == 0 ? false : true
			}
		})
		return result
	}
	/**
	 * 顶部Tab栏点击，页面滚动至指定位置
	 * @param {number} type 0页面置顶; 1滚动至评价; 2滚动至详情
	 */
	const hanleTopTabClick = (type) => {
		Data.topTabSts = type
		if (type === 0) {
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 100
			})
			return
		}
		let className = ''
		className = type === 1 ? 'comment-box' : 'det-det'
		uni.createSelectorQuery().select('.' + className).boundingClientRect(data => { // 目标节点
			uni.createSelectorQuery().select('.detail').boundingClientRect(res => { // 最外层盒子节点
				let scrollTop = 0
				if (data.top < 0) {
					scrollTop = Math.abs(res.top) - Math.abs(data.top) - 60
				} else {
					scrollTop = Math.abs(res.top) + Math.abs(data.top) - 60
				}
				uni.pageScrollTo({
					duration: 100,
					scrollTop
				})
			}).exec()
		}).exec()
	}

	/**
	 * 隐藏弹窗
	 */
	const closePopup = () => {
		Data.isShowDiscountPopup = false
		Data.isShowSkuPopup = false
		Data.skuPopConfirmType = 0
	}

	/**
	 * 立即购买
	 */
	const goSubmit = () => {
		Data.skuPopConfirmType = 2
		Data.isShowSkuPopup = true
	}

	/**
	 * 获取/更新购物车数据
	 */
	const getCartCount = () => {
		const params = {
			url: '/mall4cloud_product/a/shop_cart/prod_count',
			method: 'GET',
			data: {}
		}
		if (uni.getStorageSync('cloudToken')) {
			http.request(params).then((res) => {
				if (res) {
					Data.cartCount = res
				}
			})

		}
	}

	/**
	 * 获取观演人数据
	 */
	const getIdCardList = () => {
		const params = {
			url: '/mall4cloud_user/app/idCard/list',
			method: 'GET'
		}
		if (uni.getStorageSync('cloudToken')) {
			http.request(params).then((res) => {
				if (res) {
					Data.idCardList = res
				}
			})

		}
	}

	//选择身份证
	const selectIdCards = (id) => {
		if (Data.selectIdCard.includes(id)) {
			Data.selectIdCard = Data.selectIdCard.filter(item => item != id)
			Data.selectIdCount--
		} else {
			if (Data.selectIdCard.length == Data.prodNumber) {
				uni.showToast({
					title: '所需观演人已选齐',
					icon: 'none'
				})
				return
			}
			Data.selectIdCard.push(id)
			Data.selectIdCount++
		}
	}

	//身份证号码脱敏
	const handleIdCard = (id) => {
		return String(id).slice(0, 3) + '********' + String(id).slice(16)
	}

	const queryType = (type) => {
		return ['', '身份证', '港澳台居民居住证', '港澳居民来往内地通行证', '台湾居民来往大陆通行证', '护照', '外国人永久居留身份证'][type]
	}

	/**
	 * 去首页
	 */
	const toIndex = () => {
		const page = getCurrentPages()
		const pathname = "pages/mall-index/mall-index"
		const index = page.findIndex(item => item.route === pathname)
		/* 在页面栈中找到时 */
		const step = page.length - 1 - index
		if (step === 0) {
			uni.redirectTo({
				url: url
			})
		} else {
			uni.navigateBack({
				delta: step
			})
		}
	}

	/**
	 * 去购物车
	 */
	const toCart = () => {
		if (!uni.getStorageSync('cloudToken')) {
			uni.showModal({
				title: '提示',
				content: '该功能登录后开放哦',
				confirmText: '去登录',
				success: modalRes => {
					if (modalRes.confirm) {
						// 跳转登录页面
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}
				}
			})
			return
		}
		const page = getCurrentPages()
		const pathname = "pages/cart/cart"
		const index = page.findIndex(item => item.route === pathname)
		/* 在页面栈中找到时 */
		if (index != -1) {
			const step = page.length - 1 - index
			if (step === 0) {
				uni.redirectTo({
					url: url
				})
			} else {
				uni.navigateBack({
					delta: step
				})
			}
		} else {
			uni.navigateTo({
				url: '/pages/cart/cart'
			})
		}
	}

	/**
	 * 去店铺首页
	 */
	const toShopIndex = () => {
		uni.navigateTo({
			url: `/pages/shop-index/shop-index?shopId=${Data.shopId}`
		})
	}

	/**
	 * 弹窗
	 */
	const popupOpen = () => {
		popup.value.open();
	}

	/**
	 * 关闭弹窗
	 */
	const popupClose = () => {
		Data.cloudShopHaveView.push(Number(Data.spuId))
		uni.setStorageSync('cloudShopHaveView', Data.cloudShopHaveView)
		popup.value.close();
	}

	/**
	 * 去观演人
	 */
	const toViewer = () => {
		Data.cloudShopHaveView.push(Number(Data.spuId))
		uni.setStorageSync('cloudShopHaveView', Data.cloudShopHaveView)
		popup.value.close();
		uni.navigateTo({
			url: '/pages/my-viewer/my-viewer'
		})
	}

	// 添加图片域名
	const addDomain = (path) => {
		const resourcesUrl = import.meta.env.VITE_APP_FILE_URL
		if (!path || /^http?:\/\//.test(path)) {
			return path
		} else {
			return resourcesUrl + path
		}
	}

	/**
	 * 获取安全距离
	 */
	const securityHeight = ref(0)
	const getSecurityHeight = () => {
		let app = uni.getSystemInfoSync()
		securityHeight.value = app.statusBarHeight + 3
	}
	getSecurityHeight()

	// 开售日期（精确到2024年9月14日 08:00）
	const saleDate = new Date('2024-09-14T22:22:00');



	// 倒计时信息
	const timeLeft = ref({
		total: 0,
		days: '00',
		hours: '00',
		minutes: '00',
		seconds: '00',
	});

	// 计算剩余时间
	const calculateTimeLeft = () => {
		const now = new Date();
		const total = saleDate - now;

		if (total > 0) {
			timeLeft.value = {
				total,
				days: String(Math.floor(total / (1000 * 60 * 60 * 24))).padStart(2, '0'),
				hours: String(Math.floor((total / (1000 * 60 * 60)) % 24)).padStart(2, '0'),
				minutes: String(Math.floor((total / (1000 * 60)) % 60)).padStart(2, '0'),
				seconds: String(Math.floor((total / 1000) % 60)).padStart(2, '0'),
			};
		} else {
			timeLeft.value = {
				total: 0,
				days: '00',
				hours: '00',
				minutes: '00',
				seconds: '00'
			};
		}
	};

	// 每秒更新倒计时
	let timer;
	onMounted(() => {
		calculateTimeLeft();
		timer = setInterval(calculateTimeLeft, 1000); // 每秒刷新一次
	});

	onUnmounted(() => {
		clearInterval(timer);
	});
</script>

<style lang="scss" scoped>
	@use "shop-detail";
	@use "../../popup.scss";
</style>